<template>
  <div class="min-h-screen bg-gray-100 py-6 flex flex-col justify-center sm:py-12">
    <div class="relative py-3 sm:max-w-xl sm:mx-auto">
      <div class="relative px-4 py-10 bg-white shadow-lg sm:rounded-3xl sm:p-20">
        <div class="max-w-md mx-auto">
          <div class="divide-y divide-gray-200">
            <div class="py-8 text-base leading-6 space-y-4 text-gray-700 sm:text-lg sm:leading-7">
              <h2 class="text-2xl font-bold mb-8 text-center">用户管理</h2>
              
              <!-- 重置管理员密码 -->
              <div class="mb-8">
                <h3 class="text-lg font-semibold mb-4">重置管理员密码</h3>
                <div class="space-y-4">
                  <input
                    v-model="adminPassword"
                    type="password"
                    placeholder="新密码"
                    class="w-full px-3 py-2 border rounded-md"
                  />
                  <button
                    @click="handleResetAdminPassword"
                    :disabled="isLoading"
                    class="w-full bg-red-600 text-white py-2 px-4 rounded-md hover:bg-red-700 disabled:opacity-50"
                  >
                    {{ isLoading ? '处理中...' : '重置管理员密码' }}
                  </button>
                </div>
              </div>

              <!-- 删除所有用户 -->
              <div class="mb-8">
                <h3 class="text-lg font-semibold mb-4">删除所有用户</h3>
                <button
                  @click="handleDeleteAllUsers"
                  :disabled="isLoading"
                  class="w-full bg-red-600 text-white py-2 px-4 rounded-md hover:bg-red-700 disabled:opacity-50"
                >
                  {{ isLoading ? '处理中...' : '删除所有非管理员用户' }}
                </button>
              </div>

              <!-- 用户列表 -->
              <div>
                <h3 class="text-lg font-semibold mb-4">用户列表</h3>
                <div class="space-y-4">
                  <div v-for="user in users" :key="user.id" class="flex items-center justify-between p-3 bg-gray-50 rounded-md">
                    <div>
                      <p class="font-medium">{{ user.username }}</p>
                      <p class="text-sm text-gray-500">{{ user.email }}</p>
                    </div>
                    <button
                      v-if="user.username !== 'admin'"
                      @click="handleDeleteUser(user.id)"
                      :disabled="isLoading"
                      class="bg-red-600 text-white py-1 px-3 rounded-md hover:bg-red-700 disabled:opacity-50"
                    >
                      删除
                    </button>
                  </div>
                </div>
              </div>

              <!-- 错误提示 -->
              <div v-if="error" class="text-red-500 text-sm text-center mt-4">
                {{ error }}
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import axios from 'axios'
import { useAuthStore } from '../stores/auth'

interface User {
  id: number
  username: string
  email: string
  is_staff: boolean
}

const authStore = useAuthStore()
const users = ref<User[]>([])
const adminPassword = ref('')
const isLoading = ref(false)
const error = ref('')

// 获取用户列表
async function fetchUsers() {
  try {
    const response = await axios.get('http://localhost:8000/api/users/', {
      headers: {
        'Authorization': `Bearer ${authStore.token}`
      }
    })
    users.value = response.data
  } catch (err) {
    error.value = '获取用户列表失败'
    console.error('Error fetching users:', err)
  }
}

// 重置管理员密码
async function handleResetAdminPassword() {
  if (!adminPassword.value) {
    error.value = '请输入新密码'
    return
  }

  isLoading.value = true
  error.value = ''

  try {
    await axios.post('http://localhost:8000/api/auth/reset-admin-password/', {
      new_password: adminPassword.value
    }, {
      headers: {
        'Authorization': `Bearer ${authStore.token}`
      }
    })
    adminPassword.value = ''
    alert('管理员密码重置成功')
  } catch (err: any) {
    error.value = err.response?.data?.detail || '重置密码失败'
    console.error('Error resetting admin password:', err)
  } finally {
    isLoading.value = false
  }
}

// 删除指定用户
async function handleDeleteUser(userId: number) {
  if (!confirm('确定要删除这个用户吗？')) return

  isLoading.value = true
  error.value = ''

  try {
    await axios.delete(`http://localhost:8000/api/auth/delete-user/${userId}/`, {
      headers: {
        'Authorization': `Bearer ${authStore.token}`
      }
    })
    await fetchUsers()
    alert('用户删除成功')
  } catch (err: any) {
    error.value = err.response?.data?.detail || '删除用户失败'
    console.error('Error deleting user:', err)
  } finally {
    isLoading.value = false
  }
}

// 删除所有用户
async function handleDeleteAllUsers() {
  if (!confirm('确定要删除所有非管理员用户吗？此操作不可恢复！')) return

  isLoading.value = true
  error.value = ''

  try {
    const response = await axios.delete('http://localhost:8000/api/auth/delete-all-users/', {
      headers: {
        'Authorization': `Bearer ${authStore.token}`
      }
    })
    await fetchUsers()
    alert(response.data.detail)
  } catch (err: any) {
    error.value = err.response?.data?.detail || '删除用户失败'
    console.error('Error deleting all users:', err)
  } finally {
    isLoading.value = false
  }
}

onMounted(() => {
  fetchUsers()
})
</script> 